/*
 * Project Name spring-boot-tools
 * File Name RequestDataContext
 * Package Name com.huxiaosu.tools.mina.model
 * Create Time 2024/5/25
 * Create by name：liujie
 */
package com.huxiaosu.tools.mina.model;

import com.huxiaosu.tools.mina.utils.Constants;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/25 13:23
 */
@Slf4j
@Data
public class RequestDataContext {
    private IoBuffer ioBuffer;
    private CharsetDecoder charsetDecoder;
    private MsgType msgType;

    public RequestDataContext(String charset) {
        this.ioBuffer = IoBuffer.allocate(512).setAutoExpand(true);

        this.charsetDecoder = Constants.CHARSET_DECODER;
    }

    public String getDataAsString() {
        try {
            log.info("<case 0x1 ioBuffer={}> ", this.ioBuffer);
            this.ioBuffer.flip();
            return this.ioBuffer.getString(this.charsetDecoder);
        } catch (CharacterCodingException e) {
            return null;
        }
    }
    public byte[] getDataAsArray() {
        this.ioBuffer.flip();

        byte[] data = new byte[this.ioBuffer.remaining()];
        this.ioBuffer.get(data);

        return data;
    }

    public void append(byte[] data) {
        this.ioBuffer.put(data);
    }

}
